package com.farmlei.facereg.modules.recognition.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farmlei.facereg.common.base.SuperController;
import com.farmlei.facereg.common.result.PageResult;
import com.farmlei.facereg.modules.recognition.entity.UserInfo;
import com.farmlei.facereg.modules.recognition.service.IUserInfoService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 人员信息 前端控制器
 * </p>
 *
 * @author farmlei
 * @since 2018-10-04
 */
@Controller
@RequestMapping("")
public class UserInfoController extends SuperController {
    @Resource
    private IUserInfoService iUserInfoService;


    /**
     * 人员列表页面
     */
    @RequestMapping({"user", ""})
    String user(Model model, @RequestParam Map<String, String> params) {
        model.addAttribute("params", params);
        model.addAttribute("userList", null);
        return "userList";
    }

    /**
     * 异步分页查询人员列表
     */
    @RequestMapping("/listUser")
    @ResponseBody
    PageResult listUser(@RequestParam(defaultValue = "1") Integer pageNo,
                        @RequestParam(defaultValue = "10") Integer pageSize) {
        pageNo = pageNo / pageSize + 1;//页面上传过来的是offset，需要转成页码
        //分页查询数据
        Page<UserInfo> userPage = new Page<>(pageNo, pageSize);
        userPage = iUserInfoService.selectPageVo(userPage);

        List<UserInfo> userList = userPage.getRecords();

        return new PageResult(userList, userPage.getTotal());
    }

    /**
     * 新增用户
     */
    @RequestMapping("/addUser")
    @ResponseBody
    Map addUser(String name, String faceImg) {
        Map<String, String> result = new HashMap<>();
        try {
            UserInfo userInfo = new UserInfo();
            userInfo.setName(name);
            userInfo.setFaceImg(faceImg);

            iUserInfoService.saveUser(userInfo);
            result.put("result", "success");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", "fail");
            result.put("error", "保存失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 人脸识别验证用户
     */
    @RequestMapping("/recognizeUser")
    @ResponseBody
    Map recognizeUser(String recognizeImg) {
        Map<String, String> result = new HashMap<>();
        try {
            UserInfo userInfo = iUserInfoService.recognizeUser(recognizeImg);
            if (userInfo != null) {
                result.put("result", "success");
                result.put("name", userInfo.getName());
            } else {
                result.put("result", "fail");
                result.put("error", "未匹配到数据");
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", "fail");
            result.put("error", "验证失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 异步上传源图片
     * @param request 请求
     */
    @ResponseBody
    @RequestMapping(value = "/ajaxImageUpload",produces="text/html;charset=UTF-8")
    public String ajaxImageUpload(HttpServletRequest request) {
        Map<String, String> result = new HashMap<>();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            if (fileMap != null && fileMap.size() > 0) {
                String img_path = "";
                Map.Entry<String, MultipartFile> entity = fileMap.entrySet().iterator().next();
                // 上传文件名key对应from表单中的name值, value即为上传的文件
                MultipartFile img_cover = entity.getValue();

                String fileName = img_cover.getOriginalFilename();
                // 获取文件扩展名
                String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
                //如果文件不是图片，则不上传
                if (!"jpg".equalsIgnoreCase(ext) && !"jpeg".equalsIgnoreCase(ext)
                        && !"png".equalsIgnoreCase(ext)
                        && !"bmp".equalsIgnoreCase(ext)) {
                    throw new Exception("文件格式错误");
                }

                if (img_cover.getSize() > 0) {
                    img_path = uploadImgRenameAndComp(img_cover, "images/face/", 300);
                }
                result.put("result", "success");
                result.put("img_path", img_path);
                result.put("img_url", img_path);
            } else {
                throw new Exception("请选择要上传的文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", "fail");
            result.put("error", "文件上传失败：" + e.getMessage());
        }
        return JSON.toJSONString(result);
    }


}
